import java.util.*;

public class Solution {
    int m = 0, n = 0;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};

    public int cutOffTree(List<List<Integer>> f) {
        List<int[]> list = new ArrayList<>();

        m = f.size();
        n = f.get(0).size();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (f.get(i).get(j) > 1) {
                    list.add(new int[]{i, j});
                }
            }
        }

        Collections.sort(list, (a, b) -> {
            return f.get(a[0]).get(a[1]) - f.get(b[0]).get(b[1]);
        });

        int bx = 0, by = 0;
        int ret = 0;

        for (int[] next : list) {
            int ex = next[0];
            int ey = next[1];
            int step = bfs(f, bx, by, ex, ey);
            if (step == -1) {
                return -1;
            }
            ret += step;
            bx = ex;
            by = ey;
        }

        return ret;
    }

    public int bfs(List<List<Integer>> f, int bx, int by, int ex, int ey) {
        if (bx == ex && by == ey) {
            return 0;
        }

        Queue<int[]> q = new LinkedList<>();

        q.offer(new int[]{bx, by});

        boolean[][] flag = new boolean[m][n];

        int ret = 0;

        while (!q.isEmpty()) {
            int size = q.size();
            ret++;
            while (size > 0) {
                size--;
                int[] arr = q.poll();
                int x = arr[0];
                int y = arr[1];
                flag[x][y] = true;
                for (int i = 0; i < 4; i++) {
                    int xx = x + dx[i];
                    int yy = y + dy[i];
                    if (xx >= 0 && yy >= 0 && xx < m && yy < n && !flag[xx][yy] && f.get(xx).get(yy) > 0) {
                        if (xx == ex && yy == ey) {
                            return ret;
                        }
                        q.offer(new int[]{xx, yy});
                        flag[xx][yy] = true;
                    }
                }
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        List<Integer> list3 = new ArrayList<>();

        list1.add(1);
        list1.add(2);
        list1.add(3);

        list2.add(0);
        list2.add(0);
        list2.add(4);

        list3.add(7);
        list3.add(6);
        list3.add(5);

        List<List<Integer>> ret = new ArrayList<>();
        ret.add(list1);
        ret.add(list2);
        ret.add(list3);

        Solution solution = new Solution();
        System.out.println(solution.cutOffTree(ret));

    }
}
